﻿using lingopen.Application;
using lingopen.Application.Common;
using lingopen.Application.System;
using lingopen.Entity;
using lingopen.Entity.System;
using lingopen.Extensions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;
using System.Net.Http.Headers;

namespace lingopen.Jabil.Server.Controllers
{
    /// <summary>
    /// 登录账号管理
    /// </summary>
    public class AccountController : WebController
    {
        const string VerifyCodeKey = "session_verifycode";
        private IHostingEnvironment _hostingEnvironment;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="hostingEnvironment"></param>
        public AccountController(IHostingEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }
        /// <summary>
        /// 返回登录页面
        /// </summary>
        /// <param name="returnUrl">登录后跳转url</param>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            return View();
        }
        /// <summary>
        /// 登录验证
        /// </summary>
        /// <param name="userName">账号</param>
        /// <param name="password">密码</param>
        /// <param name="verifyCode">验证码</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Login(string userName, string password/*经过md5加密后的密码*/, string verifyCode)
        {
            //if (verifyCode.IsNullOrEmpty())
            //    return this.FailedMsg("请输入验证码");
            if (userName.IsNullOrEmpty() || password.IsNullOrEmpty())
                return this.UIFailedMsg("账号/密码不能为空");

            //string code = WebHelper.GetSession<string>(VerifyCodeKey);
            //WebHelper.RemoveSession(VerifyCodeKey);
            //if (code.IsNullOrEmpty() || code.ToLower() != verifyCode.ToLower())
            //{
            //    return this.FailedMsg("验证码错误，请重新输入");
            //}

            userName = userName.Trim();
            var accountAppService = this.CreateService<IAccountAppService>();

            const string moduleName = "系统登录";
            string ip = this.HttpContext.GetClientIP();

            Sys_User user;
            string msg;
            if (!accountAppService.CheckLogin(userName, password, out user, out msg))
            {
                this.CreateService<ISysLogAppService>().LogAsync(null, null, ip, LogType.Login, moduleName, false, "用户[{0}]登录失败：{1}".ToFormat(userName, msg));
                return this.UIFailedMsg(msg);
            }

            AdminSession session = new AdminSession();
            session.UserId = user.Id;
            session.UserName = user.UserName;
            session.RealName = user.RealName;
            session.DepartmentId = user.DepartmentId;
            session.DutyId = user.DutyId;
            session.RoleId = user.RoleId;
            session.LoginIP = ip;
            session.LoginTime = DateTime.Now;
            session.IsAdmin = user.UserName.ToLower() == AppConsts.AdminUserName;

            this.CurrentSession = session;

            this.CreateService<ISysLogAppService>().LogAsync(user.Id, user.RealName, ip, LogType.Login, moduleName, true, "登录成功");
            return this.UISuccessMsg(msg);
        }
        /// <summary>
        /// 登录验证
        /// </summary>
        /// <param name="userName">账号</param>
        /// <param name="password">密码</param>
        /// <param name="verifyCode">验证码</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Login2(string userName, string password/*经过md5加密后的密码*/, string verifyCode)
        {
            //if (verifyCode.IsNullOrEmpty())
            //    return this.FailedMsg("请输入验证码");
            if (userName.IsNullOrEmpty() || password.IsNullOrEmpty())

                return UIFailedMsg("账号/密码不能为空");
            //string code = WebHelper.GetSession<string>(VerifyCodeKey);
            //WebHelper.RemoveSession(VerifyCodeKey);
            //if (code.IsNullOrEmpty() || code.ToLower() != verifyCode.ToLower())
            //{
            //    return this.FailedMsg("验证码错误，请重新输入");
            //}

            userName = userName.Trim();
            var accountAppService = this.CreateService<IAccountAppService>();

            const string moduleName = "系统登录";
            string ip = this.HttpContext.GetClientIP();

            Sys_User user;
            string msg;
            if (!accountAppService.CheckLogin(userName, password, out user, out msg))
            {
                this.CreateService<ISysLogAppService>().LogAsync(null, null, ip, LogType.Login, moduleName, false, "用户[{0}]登录失败：{1}".ToFormat(userName, msg));

                return UIFailedMsg(msg);
            }

            AdminSession session = new AdminSession();
            session.UserId = user.Id;
            session.UserName = user.UserName;
            session.RealName = user.RealName;
            session.DepartmentId = user.DepartmentId;
            session.DutyId = user.DutyId;
            session.RoleId = user.RoleId;
            session.LoginIP = ip;
            session.LoginTime = DateTime.Now;
            session.IsAdmin = user.UserName.ToLower() == AppConsts.AdminUserName;
            session.CustomerId = user.CustomerId;
            this.CurrentSession = session;

            this.CreateService<ISysLogAppService>().LogAsync(user.Id, user.RealName, ip, LogType.Login, moduleName, true, "登录成功");
            return UISuccessData(new
            {
                access_token = session.Id
            }, msg);
        }
        /// <summary>
        /// 获取当前登录用户信息
        /// </summary>
        /// <returns></returns>
        public ActionResult GetUserInfo()
        {
            if (CurrentSession == null)
            {
                return RedirectToAction("Index");
                //return Redirect("/start/index.html#user/login"); 
            }
            return UISuccessData(new
            {
                username = this.CurrentSession.RealName,
                sex = "",
                role = this.CurrentSession.RoleId
            });
        }
         
        /// <summary>
        /// 登出
        /// </summary>
        /// <returns></returns>
        public ActionResult Logout()
        {
            this.CurrentSession = null;
            return RedirectToAction("Login");
        }
        /// <summary>
        /// 验证码
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult VerifyCode()
        {
            //string verifyCode = VerifyCodeGenerator.GenVerifyCode();
            //byte[] bytes = VerifyCodeHelper.GetVerifyCodeByteArray(verifyCode);

            //WebHelper.SetSession(VerifyCodeKey, verifyCode);

            //return this.File(bytes, @"image/Gif");
            return null;
        }

        /// <summary>
        /// 首页
        /// </summary>
        /// <returns></returns>
        [LoginAuthorizeAttribute]
        [HttpGet]
        public ActionResult Index()
        {
            var service = this.CreateService<IEntityAppService>();
            Sys_User user = service.GetByKey<Sys_User>(this.CurrentSession.UserId);
            Sys_Department department = string.IsNullOrEmpty(user.DepartmentId) ? null : service.GetByKey<Sys_Department>(user.DepartmentId);
            Sys_Duty duty = string.IsNullOrEmpty(user.DutyId) ? null : service.GetByKey<Sys_Duty>(user.DutyId);
            Sys_Role role = string.IsNullOrEmpty(user.RoleId) ? null : service.GetByKey<Sys_Role>(user.RoleId);

            UserModel model = new UserModel();
            model.User = user;
            model.DepartmentName = department == null ? null : department.Name;
            model.DutyName = duty == null ? null : duty.Name;
            model.RoleName = role == null ? null : role.Name;

            this.ViewBag.UserInfo = model;

            return View();
        }
        /// <summary>
        /// 用户基础信息
        /// </summary>
        /// <returns></returns>
        public ActionResult GetProfileInfo()
        {
            var service = this.CreateService<IEntityAppService>();
            Sys_User user = service.GetByKey<Sys_User>(this.CurrentSession.UserId);
            Sys_Role role = string.IsNullOrEmpty(user.RoleId) ? null : service.GetByKey<Sys_Role>(user.RoleId);
            // CRM_Customer cusomter = string.IsNullOrEmpty(user.CustomerId) ? null : service.GetByKey<CRM_Customer>(user.CustomerId);
            var ret = new
            {
                User = user,
                Role = role,
                // Customer = cusomter,
                url = @"/uploadfiles/img/headers/" + $"{user.Id}.png?key={Guid.NewGuid()}",
                name = user.RealName
            };
            return this.UISuccessData(ret);
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="oldPassword">明文</param>
        /// <param name="newPassword">明文</param>
        /// <returns></returns>
        [LoginAuthorizeAttribute]
        [HttpPost]
        public ActionResult ChangePassword(string oldPassword, string newPassword)
        {
            this.CreateService<IAccountAppService>().ChangePassword(oldPassword, newPassword);
            return this.UISuccessMsg("密码修改成功");
        }
        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [LoginAuthorizeAttribute]
        [HttpPost]
        public ActionResult ModifyInfo(ModifyAccountInfoInput input)
        {
            this.CreateService<IAccountAppService>().ModifyInfo(input);
            return this.UISuccessMsg("修改成功");
        }
        /// <summary>
        /// 上传头像
        /// </summary>
        /// <returns></returns>

        [HttpPost]

        public IActionResult UploadHeader()
        {
            try
            {
                var files = Request.Form.Files;
                var userId = this.CurrentSession.UserId;
                long size = 0;
                string savePath = @"\uploadfiles\img\headers";
                string url = _hostingEnvironment.WebRootPath + savePath;
                if (!Directory.Exists(url))
                {
                    Directory.CreateDirectory(url);
                }
                if (string.IsNullOrEmpty(userId))
                {
                    return UIFailedMsg("上传出错 用户信息过期,请重新登录再尝试!");
                }
                string oldfilename = "";
                string newfilename = "";
                foreach (var file in files)
                {
                    if (file == null || String.IsNullOrEmpty(file.FileName) || file.Length < 0)
                    {
                        return UIFailedMsg("上传出错 请检查文件名 或 文件内容");
                    }
                    oldfilename = ContentDispositionHeaderValue
                                    .Parse(file.ContentDisposition)
                                    .FileName
                                    .Trim('"');
                    //这个hostingEnv.WebRootPath就是要存的地址可以改下
                    newfilename = url + $@"\{userId}" + ".png";
                    size += file.Length;
                    var dirInfo = new FileInfo(newfilename).Directory;
                    if (!dirInfo.Exists)
                    {
                        dirInfo.Create();
                    }
                    using (FileStream fs = System.IO.File.Create(newfilename))
                    {
                        file.CopyTo(fs);
                        fs.Flush();
                    }
                    break;
                }
                return UISuccessData(new { url = @"/uploadfiles/img/headers/" + $"{userId}.png?key={Guid.NewGuid()}", name = oldfilename }, $"{oldfilename}/{size} bytes 已上传成功!");
            }
            catch { }
            return UIFailedMsg("上传出错");
        }
    }
    /// <summary>
    /// 用户信息
    /// </summary>
    public class UserModel
    {
        /// <summary>
        /// 用户信息
        /// </summary>
        public Sys_User User { get; set; }
        /// <summary>
        /// 部门名称
        /// </summary>
        public string DepartmentName { get; set; }
        /// <summary>
        /// 岗位名称
        /// </summary>
        public string DutyName { get; set; }
        /// <summary>
        /// 角色名称
        /// </summary>
        public string RoleName { get; set; }
    }
}